package org.sunshine.dye.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.sunshine.dye.base.Constants;

@Configuration
public class SunshineDyeConfig implements WebMvcConfigurer {

	// 配置跨域过滤器
	@Bean
	public FilterRegistrationBean<CorsFilter> corsFilter() {

		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

		final CorsConfiguration config = new CorsConfiguration();
		// 允许cookies跨域
		config.setAllowCredentials(true);

		// 允许向该服务器提交请求的URI，*表示全部允许，在SpringMVC中，如果设成*，会自动转成当前请求头中的Origin
		config.addAllowedOrigin("*");

		// 允许访问的头信息,*表示全部
		config.addAllowedHeader("*");

		// 预检请求（options请求）的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
		config.setMaxAge(1L);

		// 允许提交请求的方法，*表示全部允许
		config.addAllowedMethod("*");
		/*
		 * config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD");
		 * config.addAllowedMethod("GET"); config.addAllowedMethod("PUT");
		 * config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE");
		 * config.addAllowedMethod("PATCH");
		 */

		// 设置允许跨域的路径
		source.registerCorsConfiguration("/**", config);

		FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<CorsFilter>(new CorsFilter(source));

		// 设过滤器的优先级
		bean.setOrder(0);

		return bean;
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		registry.addInterceptor(loginIntercepter()).addPathPatterns("/**").excludePathPatterns("/safty/login/**");

		registry.addInterceptor(nocacheInterceptor()).addPathPatterns("/**");
	}
	
	//登录拦截器
	private HandlerInterceptor loginIntercepter() {

		return new HandlerInterceptor() {

			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {

				Object currUser = request.getSession().getAttribute(Constants.SESSION_ATTR_CURR_USER);

				if (currUser == null) {

					response.sendRedirect(request.getContextPath() + "/safty/login/loginTo");

					return false;
				}

				return true;

			}
		};
	}

	// 禁用浏览器缓存拦截器
	public HandlerInterceptor nocacheInterceptor() {

		return new HandlerInterceptor() {

			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {

				response.addHeader("Pragma", "no-cache");
				response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
				response.addHeader("Cache-Control", "pre-check=0, post-check=0");
				response.setDateHeader("Expires", 0);

				return true;

			}
		};

	}
}
